<template>
  <!-- 顶部导航栏 -->
  <div>
    <van-nav-bar title="首页" fixed/>
  </div>

  <!-- 内容容器 -->
  <div class="content-wrapper" @click="goToSelectAllDoctor">
    <!-- 选医生模块 -->
    <section class="module doctor-select">
      <div class="module-content">
        <van-icon name="manager" color="#1989fa" size="50" />
        <div class="text-group">
          <h2 class="title">选医生</h2>
          <p class="subtitle">科室千余位医生</p>
        </div>
      </div>
    </section>

    <!-- 预约挂号模块 -->
    <section class="module appointment">
      <div class="module-header">
        <div class="title-group">
          <h2>预约挂号</h2>
          <span class="subtitle">一站式服务挂号平台</span>
        </div>
        <div class="more">
          <span @click="goToDepartmentSelector">全部科室</span>
          <van-icon name="arrow" color="#1989fa" />
        </div>
      </div>
      
      <!-- 加载状态 -->
      <van-empty v-if="loading" description="加载中..." />
      <van-empty v-if="!loading && departments.length === 0" description="暂无科室数据" />
      
      <!-- 科室列表 -->
      <van-swipe v-else class="swipe-container" :loop="false">
        <van-swipe-item
          v-for="page in Math.ceil(departments.length / 12)"
          :key="page"
        >
          <van-grid :column-num="4" :border="false" :row-num="3">
            <van-grid-item
              v-for="(department, index) in departments.slice(
                (page - 1) * 12,
                page * 12
              )"
              :key="index"
              @click="goToSelectDoctor(department)"
            >
              <template #icon>
                <van-icon name="user-o" color="#4395ff" size="24" />
              </template>
              <template #text>
                <span class="grid-text">{{ department }}</span>
              </template>
            </van-grid-item>
          </van-grid>
        </van-swipe-item>
      </van-swipe>
    </section>

    <!-- 专科专区模块 -->
    <!-- <section class="module special-area">
      <h2 class="title">专科专区</h2>
      <div class="special-area-wrapper">
        <van-grid :column-num="2" :gutter="10" :border="false">
          <van-grid-item v-for="item in 4" :key="item" class="special-card">
            <van-icon name="cluster-o" size="30" />
            <div class="card-text">
              <h3>心血管科</h3>
              <p>专家团队坐诊</p>
            </div>
          </van-grid-item>
        </van-grid>
      </div>
    </section> -->

    <!-- 健康热点模块 -->
    <section class="module health-news">
      <div class="module-header">
        <div class="title-group">
          <h2>健康热点</h2>
          <span class="more" src="https://health.china.com/"
          >科普健康知识不再小白></span
          >
        </div>
      </div>
      <div class="news-list">
        <div class="footer">
          <van-list
              :loading="loading"
              :finished="finished"
              finished-text="没有更多了"
              @load="getList()"
          >
            <div
                style="height: 5vw; margin-top: 8vw"
                v-for="item in healthList"
                :key="item.id"
            >
              <van-row
                  style="height: 100%"
                  :gutter="[10, 0]"
                  justify="space-around"
                  @click="openNews(item.url)"
              >
                <van-col span="4">
                  <van-image
                      width="50"
                      height="50"
                      fit="cover"
                      :src="item.picUrl"
                  />
                </van-col>
                <van-col span="18">
                  <p>{{ item.title }}</p>
                </van-col>
              </van-row>
            </div>
          </van-list>
        </div>
      </div>
    </section>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useUserStore } from "../stores/user.js";
import { getHealthList } from "../api/health/newsRequest.js";
import { getAllDepartmentNames } from "../api/department/departmentRequest.js";
import { useRouter } from "vue-router";
import { showToast } from 'vant';

const userStoreAPI = useUserStore();
const router = useRouter();

// 科室相关数据
const departments = ref([]);
const loading = ref(true);

// 获取科室列表
const fetchDepartments = async () => {
  try {
    const res = await getAllDepartmentNames();
    if (res.success) {
      departments.value = res.data;
    } else {
      showToast(res.errMsg || '获取科室列表失败');
    }
  } catch (error) {
    console.error("获取科室列表失败:", error);
    showToast('获取科室列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 定义跳转方法
const goToDepartmentSelector = () => {
  router.push("/departmentSelector");
};

const goToSelectDoctor = (department) => {
  router.push({ 
    path: '/selectDoctor',
    query: { department } 
  });
};

const goToSelectAllDoctor = () => {
  // 移除这个点击事件，避免整个页面都跳转到选医生页面
  // router.push({ name: "选医生" });
};


const healthList = ref([]);
const finished = ref(false);
const page = ref(1);
const topFiveImages = ref([]); // 新增：用于存储前五张图片的链接
const swipeHeight = ref("200px"); // 新增：设置轮播图的高度

// 请求获取头条新闻数据
const getList = () => {
  loading.value = true; // 开始加载数据
  console.log("开始请求数据，当前页码:", page.value);

  getHealthList({
    // key: "97a147379202826dd4ca3efbb9ccb49f",
    key: "53d8c8cad64903d85195926c8745324e",
    num: 3,
    page: page.value, // 当前页码
  })
      .then((res) => {
        console.log("接口返回数据:", res);
        if (!res || !res.result || !res.result.newslist) {
          console.error("后端接口返回数据异常:", res);
          finished.value = true;
          loading.value = false;
          return;
        }

        if (res.result.newslist.length) {
          console.log("成功获取数据，新增数据数量:", res.result.newslist.length);
          healthList.value = [...healthList.value, ...res.result.newslist];
          topFiveImages.value = healthList.value
              .slice(0, 3)
              .map((item) => item.picUrl);

          page.value++;
          loading.value = false;
        } else {
          console.log("没有更多数据");
          finished.value = true;
          loading.value = false;
        }
      })
      .catch((error) => {
        console.error("接口请求失败:", error);
        finished.value = true;
        loading.value = false;
      });
};

// 上一张图片
const prevSlide = () => {
  this.$refs.swipeRef.prev();
};

// 下一张图片
const nextSlide = () => {
  this.$refs.swipeRef.next();
};

// 在当前窗口打开新闻链接
const openNews = (url) => {
  if (url) {
    window.open(url, "_self");
  }
};

// 初始化数据
getList();
// 组件挂载时获取数据
onMounted(() => {
  fetchDepartments();
  getList(); // 获取健康资讯列表
});
</script>

<style scoped>
html,
body {
  margin: 0;
  padding: 0;
  background-color: #fff;
}
h3 {
  margin: 0;
  font-size: 16px;
}
p {
  margin: 5px 0 0;
  color: #646566;
}
.content-wrapper {
  padding: 0 3%;
}

.module {
  width: 100%;
  margin: 0 auto 10px;
  border-radius: 12px;
  padding: 5px;
  box-sizing: border-box;
}

/* 顶部导航栏样式 */
.share-box {
  display: flex;
  align-items: center;
  border: 1px solid #ebedf0;
  border-radius: 10px;
}

.divider {
  width: 1px;
  height: 20px;
  background: #d8dade;
  margin: 0 12px;
}

.doctor-select,
.appointment,
.special-area,
.hot-doctor,
.health-news {
  background: linear-gradient(to bottom, #e6f0ff, #ffffff);
}
:deep(.van-grid-item__content) {
  padding: 8px; /* 缩小格子间隔 */
  background-color: transparent !important;
}
/* 选医生模块 */
.module-content {
  margin: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.text-group {
  margin-left: 20px;
  display: inline-block;
}

.title {
  font-size: 20px;
  margin: 0;
}

.subtitle {
  color: #969799;
  font-size: 14px;
}

/* 预约挂号模块 */
.module-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 10px;
}
.title-group {
  display: flex;
  align-items: center;
  gap: 10px;
}
.title-group h2 {
  margin: 0 2px 0 0;
  font-size: 20px;
}
.more {
  color: #1989fa;
  display: flex;
  align-items: center;
}
.appointment .swipe-container {
  height: 200px;
}

/* 专科专区模块 */
.special-area {
  background: linear-gradient(to bottom, #e6f0ff, #ffffff);
}

.special-area .title {
  margin: 10px;
  color: #facc7c;
}

.special-area .special-card {
  color: #3ba6ca;
}

.special-area .special-card .card-text {
  margin-left: 10px;
}

.special-area .special-card .card-text p {
  margin: 5px 0 0;
  font-size: 12px;
}

/* 健康热点模块 */
.health-news .news-list .news-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0px 10px;
  height: 9vh;
  border-bottom: 1px solid #ebedf0;
}

.health-news .news-list .news-card .news-text {
  flex: 1;
}
</style>
